package com.yonyou.service.demo.web;

import com.yonyou.service.demo.Consts;
import com.yonyou.service.demo.exception.APPIdException;
import com.yonyou.service.demo.service.APPIdService;
import com.yonyou.service.demo.service.TokenService;
import com.yonyou.service.demo.util.ParamBean;
import com.yonyou.service.demo.util.RestResult;
import com.yonyou.service.demo.util.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("uapws/rest/gl")
public class ApiController {

    @Autowired
    APPIdService appIdService;

    @Autowired
    TokenService tokenService;

    @RequestMapping("/gettoken")
    @ResponseBody
    public RestResult getToken(HttpServletRequest request) {
        String appId = request.getHeader(Consts.APPID);
        if (Utils.isEmptyString(appId)) {
            return RestResult.errorResult("App Id not found");
        }
        String message = "";
        try {
            if (appIdService.checkAppId(appId)) {
                return RestResult.successResult(tokenService.buildToken(appId));
            }
        } catch (APPIdException e) {
            message = e.getMessage();
        } catch (Exception e) {
            message = e.getMessage();
        }
        return RestResult.errorResult(message);
    }

    @RequestMapping("/query")
    @ResponseBody
    public RestResult query(@RequestBody ParamBean paramBean, HttpServletRequest request) {
        String appId = request.getHeader(Consts.APPID);
        String token = request.getHeader(Consts.TOKEN);
        if (Utils.isEmptyString(appId) || Utils.isEmptyString(token)) return RestResult.errorResult("App id or token is invalid");
        if (!tokenService.checkToken(appId, token)) return RestResult.errorResult("token is invalid (maybe timeout) ");

        // 以下应该数据服务细节，这里没有写，显示参数，然后直接返回一个成功的信息
        System.out.printf("Table name: %s\n", paramBean.getTable());
        System.out.printf("Where condition: %s\n", paramBean.getWhere());
        System.out.printf("Page index: %d\n", paramBean.getPage());
        return RestResult.successResult("返回数据成功，这里没有数据，仅仅是个示例");
    }
}
